package com.ljh.mboxvidoserver.system.interceptor;

import com.ljh.mboxvidoserver.common.result.entity.Result;
import com.ljh.mboxvidoserver.system.entity.LoginUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession(false);

        Result result = new Result();

        if (session == null) {

            Boolean isTimeout = (Boolean) request.getServletContext().getAttribute("session-timeout");

            result.setResult("/error_auto.html");
            if(isTimeout!=null && isTimeout) {
                result.setMessage("登陆超时，请重新登陆");
            }else {
                result.setMessage("您尚未登录系统");
            }
            request.setAttribute("result",result);

            request.getRequestDispatcher("/system/error").forward(request, response);

//          response.sendRedirect("/session_timeout.html");

            return false;
        }

        LoginUser loginUser = (LoginUser) session.getAttribute("loginUser");

        if (loginUser == null) {

            result.setResult("/error_auto.html");

            result.setMessage("您尚未登陆系统");

            request.setAttribute("result",result);

            request.getRequestDispatcher("/system/error").forward(request, response);

            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
